import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Iterator;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TreeMap;


public class TwoModelCombiner {
	
	private TreeMap<Integer, Integer> distributionFreq;
	private TreeMap<Integer, Integer> distributionNGram;
	private TreeMap<Integer, Integer> distributionCombine;
	
	//combine freq_distance_me.csv and ngram_distance_me.csv
	public TwoModelCombiner(String freqDistanceFile, String ngramDistanceFile){
		try {
			this.distributionFreq = new TreeMap<Integer, Integer>();			
			BufferedReader brFreq = new BufferedReader(new FileReader(freqDistanceFile));
			String oneLineFreq;
			while((oneLineFreq=brFreq.readLine())!=null){
				StringTokenizer stFreq = new StringTokenizer(oneLineFreq,",");
				String xStr = stFreq.nextToken();
				String yStr = stFreq.nextToken();
				int x = Integer.parseInt(xStr);
				int y = Integer.parseInt(yStr);
				this.distributionFreq.put(x, y);
			}
			
			
			this.distributionNGram = new TreeMap<Integer, Integer>();
			BufferedReader brNGram = new BufferedReader(new FileReader(ngramDistanceFile));
			String oneLineNGram;
			while((oneLineNGram=brNGram.readLine())!=null){
				StringTokenizer stNGram = new StringTokenizer(oneLineNGram,",");
				String xStr = stNGram.nextToken();
				String yStr = stNGram.nextToken();
				int x = Integer.parseInt(xStr);
				int y = Integer.parseInt(yStr);
				this.distributionNGram.put(x, y);
			}
			
			
			this.distributionCombine = new TreeMap<Integer, Integer>();
			
			Iterator ite1 = this.distributionFreq.entrySet().iterator();
			while(ite1.hasNext()){
				Map.Entry entry = (Map.Entry)ite1.next();
				int x = (Integer)entry.getKey();
				int y = (Integer)entry.getValue();
				if(this.distributionCombine.containsKey(x)){
					int tmp = this.distributionCombine.get(x);
					this.distributionCombine.put(x, tmp+y);
					System.err.println("somethig wrong...");
				}
				else{
					this.distributionCombine.put(x, y);
				}
			}
			
			Iterator ite2 = this.distributionNGram.entrySet().iterator();
			while(ite2.hasNext()){
				Map.Entry entry = (Map.Entry)ite2.next();
				int x = (Integer)entry.getKey();
				int y = (Integer)entry.getValue();
				if(this.distributionCombine.containsKey(x)){
					int tmp = this.distributionCombine.get(x);
					this.distributionCombine.put(x, tmp+y);
				}
				else{
					this.distributionCombine.put(x, y);
				}
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
	
	public void displayMapForDistance(String outputFileName){
		IDSAnomalyDetector ad = new IDSAnomalyDetector();
		ad.displayMap(this.distributionCombine, outputFileName);
	}

}
